package com.von.nhcf.util;

import com.aliyun.api.gateway.demo.util.HttpUtils;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 短信服务工具类
 * @author von
 */
public class SendSmsUtil {
    static Logger logger = LoggerFactory.getLogger(SendSmsUtil.class);
    /**
     * 短信发送方法
     * @param codeCount 验证码位数
     * @param appcode 短信功能服务码
     * @param mobile 目标用户电话号码
     * @param smsSignId 短信签名
     * @param templateId 短信模板
     * @return 成功：返回验证码，失败或异常：返回描述信息
     */
    public static ResultEntity sendSms(int codeCount, String appcode, String mobile, String smsSignId, String templateId) {
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        //生成验证码
        if (codeCount <= 4) {
            codeCount = 4;
        }
        String code = buildRandomCode(codeCount);
        // 添加短信属性
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        querys.put("param", "**code**:" + code + ",**minute**:5");
        querys.put("smsSignId", smsSignId);
        querys.put("templateId", templateId);
        Map<String, String> bodys = new HashMap<String, String>();

        HttpResponse response = null;
        try {
            response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            StatusLine statusLine = response.getStatusLine();
            String reasonPhrase = statusLine.getReasonPhrase();
            int statusCode = statusLine.getStatusCode();
            logger.debug(response.toString());
            logger.debug(EntityUtils.toString(response.getEntity()));
            int status = 200;
            // 发送成功返回验证码
            if (statusCode == status) {
                return ResultEntity.successWithData(code);
            }
            return ResultEntity.failureWithMsg(reasonPhrase);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultEntity.failureWithMsg(e.getMessage());
        }
    }

    /**
     * 随机验证码生成方法
     * @param count 验证码位数
     * @return 验证码
     */
    private static String buildRandomCode(int count) {
        StringBuilder codeBuilder = new StringBuilder();
        for (int i = 0; i < count; i++) {
            int codeFactor = (int) (Math.random() * 10);
            codeBuilder.append(codeFactor);
        }
        String code = codeBuilder.toString();

        return code;
    }
}
